﻿using Newtonsoft.Json;
using RTW.OA.Areas.System.Servers;
using RTW.OA.Models;
using RTW.Utils.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Web.Mvc;

namespace RTW.OA.Areas.System.Controllers
{
    public class RoleController : Controller
    {
        private RoleServers roleServers;

        public RoleController()
        {
            roleServers = new RoleServers();
        }

        // GET: System/Role
        public ActionResult Index()
        {
            return View();
        }

        // GET: System/Role/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: System/Role/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: System/Role/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: System/Role/Edit/5
        public ActionResult Edit(int? id)
        {
            ViewBag.TreeData = DeptTreeData();
            var model = new role();
            if (id != null)
            {
                ViewBag.Title = "编辑角色";
                model = GetRoleModel(id.Value.ToString());
            }
            else
            {
                ViewBag.Title = "新建角色";
                model = GetRoleModel();
            }

            return View(model);
        }

        // POST: System/Role/Edit/5
        [HttpPost]
        public ActionResult Edit(int? id, role model)
        {
            ViewBag.TreeData = DeptTreeData();
            try
            {
                if (id == null || id == 0)
                {
                    roleServers.Add(model);
                    ViewBag.msg = "新增角色信息成功！";
                    //model = new role();
                }
                else
                {
                    roleServers.Update(model);
                    ViewBag.msg = "修改角色信息成功！";
                }
            }
            catch
            {
                ViewBag.msg = "提交出现错误！";
            }

            return View(model);
        }

        // GET: System/Role/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: System/Role/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        #region //GetDate

        public string GetTableJsonResult()
        {
            var list = roleServers.GetRoles();

            return JsonConvert.SerializeObject(list);
        }

        public role GetRoleModel(string id = null)
        {
            var model = new role();
            if (id != null)
                model = roleServers.GetRoleById(id);

            model.FUNC_ID_MENU = roleServers.GetMenus();
            foreach (var menu in model.FUNC_ID_MENU)
            {
                menu.MENU_ACTION = roleServers.GetMenuActions(menu.MENU_ID);
            }
            model.FUNC_ID_ACTION = GetAllActionByAssembly();
            return model;
        }

        #region 绑定部门=============================

        private List<SelectListItem> DeptTreeData()
        {
            List<SelectListItem> menus = new List<SelectListItem>();
            var list = roleServers.GetDepts();             
            menus.Clear();
            menus.Add(new SelectListItem() { Value = "0", Text = "无父级部门" });

            foreach (var dr in list)
            {
                string Id = dr.DEPT_ID.ToString();
                int ClassLayer = int.Parse(dr.LEVEL.ToString());
                string Title = dr.DEPT_NAME.ToString().Trim();

                if (ClassLayer == 0)
                {
                    menus.Add(new SelectListItem { Value = Id, Text = Title });
                }
                else
                {
                    Title = "├ " + Title;
                    Title = StringUtil.StringOfChar(ClassLayer, "　") + Title;
                    menus.Add(new SelectListItem { Value = Id, Text = Title });
                }
            }

            return menus;
        }

        #endregion 绑定部门=============================


        public List<actionpermission> GetAllActionByAssembly()
        {
            var result = new List<actionpermission>();

            var types = Assembly.Load("RTW.OA").GetTypes();

            foreach (var type in types)
            {
                if (type.BaseType.Name == "BaseController")//如果是Controller
                {

                    var ap = new actionpermission
                    {
                        ACTIONNAME = new List<string>(),
                        CONTROLLER = type.Name.Substring(0, type.Name.Length - 10)
                    };
                    ;/*member.DeclaringType.Name.Substring(0, member.DeclaringType.Name.Length - 10); */// 去掉“Controller”后缀
                    var members = type.GetMethods();
                    foreach (var member in members)
                    {
                        if (member.ReturnType.Name == "ActionResult")//如果是Action
                        {

                            object[] Attributes = member.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true);
                            if (Attributes.Length > 0)
                            {
                                ap.ACTIONNAME.Add(Attributes[0].ToString().Replace("System.Web.Mvc.",string.Empty).Replace("Attribute",string.Empty) + "_" + member.Name);
                            }
                            else
                            {
                                ap.ACTIONNAME.Add(member.Name);
                            }
                            

                            object[] attrs = member.GetCustomAttributes(typeof(DescriptionAttribute), true);
                            if (attrs.Length > 0)
                                ap.DESCRIPTION = (attrs[0] as DescriptionAttribute).Description;

                            
                        }

                    }
                    result.Add(ap);
                }
            }
            return result;
        }
        #endregion //GetDate
    }
}